/* eslint-disable*/
import React, { useState, useEffect, useImperativeHandle, useRef } from 'react';
import Hls from 'hls.js';
import fucs from './fucs';
import Game from './class/Game';
import CONFIG from './config';
import Select from '../Select';
import Button from '../Button';
import NumberInput from '../NumberInput';
import { Slider } from 'antd';

import './index.less';
import { message } from 'antd';
import moment from 'moment';

const iconMap: any = {
  play: 'https://dpubstatic.udache.com/static/dpubimg/5A_KYoZ4xr/tianlai_icon_bofang_normal.png',
  paused:
    'https://dpubstatic.udache.com/static/dpubimg/lv0fJx3d9k/tianlai_icon_bofang_active.png',
  jumpLeft:
    'https://dpubstatic.udache.com/static/dpubimg/5XC6oidIqZ/tianlai_icon_houtui.png',
  jumpRight:
    'https://dpubstatic.udache.com/static/dpubimg/MXtROuae97/tianlai_icon_qianjin.png',
  volume:
    'https://dpubstatic.udache.com/static/dpubimg/EEjz6TO4MI/tianlai_icon_yinliang.png'
};

export default (props: any) => {
  const {
    m3u8,
    images,
    cRef,
    startTime,
    YYYYMMDDStartTime,
    handleMouseRightClick,
    canvasPlayingFuc,
    canvasJumpFuc,
    onAudioPlayOrPause,
    onAudioPlaybackRateChange,
    onAudioVolumeChange,
    onAudioJumpButtonClick,
    onAudioReady,
    onClickPlayBtn
  } = props;
  const wrapperRef = useRef<HTMLDivElement>(null!);
  const [isInit, setIsInit] = useState<boolean>(false);
  const [oVideo, setOVideo] = useState<HTMLMediaElement>(null!);
  const [isPaused, setIsPaused] = useState<boolean>(true);
  const [game, setGame] = useState<any>();
  const [audioCurrentTime, setAudioCurrentTime] = useState<any>(
    '2021-01-01 00:00:00'
  );
  const [jumpTimeLeftSelectValue, setJumpTimeLeftSelectValue] =
    useState<string>('5');
  const [jumpTimeRightSelectValue, setJumpTimeRightSelectValue] =
    useState<string>('5');
  const [hValue, setHValue] = useState<any>();
  const [mValue, setMValue] = useState<any>();
  const [sValue, setSValue] = useState<any>();
  const [multipleValue, setMultipleValue] = useState('1');
  const [sliderValue, setSliderValue] = useState(100);

  const jumpTimeOptions = [
    {
      id: 1,
      label: '1s'
    },
    {
      id: 3,
      label: '3s'
    },
    {
      id: 5,
      label: '5s'
    }
  ];

  const multipleOptions = [
    {
      id: 0.5,
      label: '0.5x'
    },
    {
      id: 0.75,
      label: '0.75x'
    },
    {
      id: 1,
      label: '1.0x'
    },
    {
      id: 1.25,
      label: '1.25x'
    },
    {
      id: 1.5,
      label: '1.5x'
    },
    {
      id: 2,
      label: '2x'
    }
  ];

  useImperativeHandle(cRef, () => {
    return {
      setGameCurrentTime,
      propsSetAudioPlayingStatus,
      handleChangeSlider,
      getAudioDuration
    };
  });

  // 初始化canvas 2
  useEffect(() => {
    (async () => {
      if (
        oVideo &&
        Array.isArray(images) &&
        images.length &&
        moment(startTime, 'HH:mm:ss').isValid()
      ) {
        const _width = wrapperRef.current.offsetWidth;
        const width = _width < CONFIG.canvasWidth ? CONFIG.canvasWidth : _width;
        const oCanvas = document.getElementById(
          CONFIG.canvasId
        ) as HTMLCanvasElement;
        oCanvas.width = width;
        const dpr = fucs.initCvsDpr(CONFIG.canvasId);
        const game = new Game({
          canvasConfig: {
            id: CONFIG.canvasId,
            x: 0,
            y: 0,
            width: width,
            height: CONFIG.canvasHeight,
            bgColor: CONFIG.canvasBgColor
          },
          imgScaleX: width / CONFIG.canvasWidth,
          dpr,
          oVideo,
          images,
          startTime,
          YYYYMMDDStartTime,
          handleMouseRightClick,
          propsAudioPlayingFuc,
          propsAudioCanvasClickFuc
        });
        await game.init();
        setGame(game);
      }
    })();
  }, [oVideo, images, startTime]);

  // 加载音频 1
  useEffect(() => {
    if (m3u8 && wrapperRef.current) {
      const oVideo = document.getElementById(
        CONFIG.videoId
      ) as HTMLMediaElement;
      if (Hls.isSupported()) {
        const hls = new Hls();
        hls.loadSource(m3u8);
        hls.attachMedia(oVideo);
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          setOVideo(oVideo);
        });
      }
    }
  }, [m3u8, wrapperRef.current]);

  useEffect(() => {
    if (YYYYMMDDStartTime && YYYYMMDDStartTime !== audioCurrentTime) {
      setAudioCurrentTime(YYYYMMDDStartTime);
    }
  }, [YYYYMMDDStartTime]);

  useEffect(() => {
    if (game && !isInit) {
      onAudioReady(true);
      setIsInit(true);
    }
  }, [game, isInit]);

  const getAudioDuration = () => game?.oVideo?.duration;

  const propsAudioPlayingFuc = (ev: any = {}) => {
    const { relativeTime } = ev;
    setAudioCurrentTime(relativeTime);
    canvasPlayingFuc(ev);
  };

  const propsAudioCanvasClickFuc = (e: any) => canvasJumpFuc(e);

  const handleJumpSecondClick = (type: string) => {
    if (isVoiceMsgErr()) {
      return;
    }
    switch (type) {
      case 'left':
        canvasJumpFuc(game.jumpLeft(+jumpTimeLeftSelectValue));
        break;
      case 'right':
        canvasJumpFuc(game.jumpRight(+jumpTimeRightSelectValue));
        break;
      default:
        break;
    }
  };

  const isVoiceMsgErr = () => {
    if (!oVideo) {
      message.error('音频加载失败！');
      return true;
    }
    return false;
  };

  const propsSetAudioPlayingStatus = (status: string) => {
    if (isVoiceMsgErr() || !['play', 'pause'].includes(status)) {
      return;
    }
    if (status === 'play') {
      game.play();
      setIsPaused(false);
      onAudioPlayOrPause('play');
    } else {
      game.pause();
      setIsPaused(true);
      onAudioPlayOrPause('pause');
    }
  };

  const handleClickAudioPlay = () => {
    if (isVoiceMsgErr()) {
      return;
    }

    if (game.paused()) {
      game.play();
      setIsPaused(false);
      onAudioPlayOrPause('play');
      onClickPlayBtn('play');
    } else {
      game.pause();
      setIsPaused(true);
      onAudioPlayOrPause('pause');
      onClickPlayBtn('pause');
    }
  };

  const handleChangePlaybackRate = (ev: any) => {
    if (isVoiceMsgErr()) {
      return;
    }
    setMultipleValue(ev);
    onAudioPlaybackRateChange(+ev);
    game.setPlaybackRate(+ev);
  };

  const handleChangeSlider = (ev: any) => {
    if (isVoiceMsgErr()) {
      return;
    }
    setSliderValue(ev);
    game.setVolume(ev / 100);
    onAudioVolumeChange(ev);
  };

  const computedHHmmssToNumber = (time: string) => {
    const t = moment(time, 'HH:mm:ss');
    return t.get('hour') * 60 * 60 + t.get('minute') * 60 + t.get('second');
  };

  const handleJumpSetTime = () => {
    if (isVoiceMsgErr()) {
      return;
    }
    const h = hValue ? hValue * 60 * 60 : 0;
    const m = mValue ? mValue * 60 : 0;
    const s = sValue ? sValue : 0;
    const time = h + m + s;
    return setGameCurrentTime(time, true);
  };

  const setGameCurrentTime = (time: number, play = false) => {
    if (typeof time !== 'number') {
      message.error('无效的音频时间！');
      return;
    }
    if (!game) {
      message.error('音频加载失败！');
      return;
    }
    let videoBusinessLastTime = computedHHmmssToNumber(
      game.lastTime().fromStartTimeTime
    );
    const videoBusinessStartTime = computedHHmmssToNumber(startTime);
    if (videoBusinessLastTime <= videoBusinessStartTime) {
      videoBusinessLastTime += 60 * 60 * 24;
    }
    if (time < videoBusinessStartTime) {
      time += 60 * 60 * 24;
    }
    if (time < videoBusinessStartTime || time > videoBusinessLastTime) {
      message.error('超出音频播放范围！');
      return;
    }

    const currentNumberTime = time - videoBusinessStartTime;
    const returnTime = game.setCurrentTime(Math.floor(currentNumberTime));
    canvasJumpFuc(returnTime);

    if (play && game.paused()) {
      game.play();
      onAudioPlayOrPause('play');
      setIsPaused(false);
    }
    return returnTime;
  };

  return (
    <div className={'X-audioCanvas'} ref={wrapperRef}>
      <video id={'X-audio-video'} />
      <canvas
        id={CONFIG.canvasId}
        width={CONFIG.canvasWidth}
        height={CONFIG.canvasHeight}
        style={{}}
      >
        您的浏览器不支持canvas，请使用最新版Chrome！
      </canvas>
      <div className={'X-audioCanvas-options'}>
        <div className={'X-audioCanvas-options-left'}>
          <div className={'X-audioCanvas-options-currentTime'}>
            {audioCurrentTime}
          </div>
          <NumberInput
            style={{
              width: '50px'
            }}
            max={24}
            min={0}
            size={'small'}
            placeholder={'时'}
            precision={0}
            value={hValue}
            onChange={setHValue}
          />
          <div
            className={'X-audioCanvas-options-jumpMsg'}
            style={{
              padding: '0 4px'
            }}
          >
            :
          </div>
          <NumberInput
            style={{
              width: '50px'
            }}
            max={59}
            min={0}
            size={'small'}
            placeholder={'分'}
            precision={0}
            value={mValue}
            onChange={setMValue}
          />
          <div
            className={'X-audioCanvas-options-jumpMsg'}
            style={{
              padding: '0 4px'
            }}
          >
            :
          </div>
          <NumberInput
            style={{
              width: '50px',
              marginRight: '10px'
            }}
            max={59}
            min={0}
            size={'small'}
            placeholder={'秒'}
            precision={0}
            value={sValue}
            onChange={setSValue}
          />
          <Button
            onClick={() => {
              const time = handleJumpSetTime();
              onAudioJumpButtonClick(
                time ? { ...time, play: true } : { play: false }
              );
            }}
            size={'small'}
            text={'跳转'}
            style={{
              backgroundColor: 'rgb(84, 191, 162)',
              border: 'none'
            }}
          />
          <div
            className={
              'X-audioCanvas-options-jumpIcon X-audioCanvas-options-jumpLeftIcon'
            }
            style={{
              backgroundImage: `url("${iconMap.jumpLeft}")`
            }}
            onClick={() => handleJumpSecondClick('left')}
          />
          <div
            style={{
              marginRight: '10px'
            }}
          >
            <Select
              size={'small'}
              width={50}
              placeholder={''}
              showArrow={false}
              allowClear={false}
              showSearch={false}
              options={jumpTimeOptions}
              value={jumpTimeLeftSelectValue}
              onChange={setJumpTimeLeftSelectValue}
            />
          </div>
          <div
            className={'X-audioCanvas-options-play'}
            style={{
              backgroundImage: `url("${iconMap[isPaused ? 'play' : 'paused']}")`
            }}
            onClick={() => handleClickAudioPlay()}
          />
          <div style={{ marginLeft: '10px' }}>
            <Select
              size={'small'}
              width={50}
              placeholder={''}
              showArrow={false}
              allowClear={false}
              showSearch={false}
              options={jumpTimeOptions}
              value={jumpTimeRightSelectValue}
              onChange={setJumpTimeRightSelectValue}
            />
          </div>
          <div
            className={
              'X-audioCanvas-options-jumpIcon X-audioCanvas-options-jumpRightIcon'
            }
            style={{
              backgroundImage: `url("${iconMap.jumpRight}")`
            }}
            onClick={() => handleJumpSecondClick('right')}
          />
        </div>
        <div className={'X-audioCanvas-options-right'}>
          <Select
            size={'small'}
            width={60}
            placeholder={''}
            showArrow={false}
            allowClear={false}
            showSearch={false}
            options={multipleOptions}
            value={multipleValue}
            onChange={(ev: any) => handleChangePlaybackRate(ev)}
          />
          <div className={'X-audioCanvas-options-volume'}>
            <div
              className={'X-audioCanvas-options-volume-icon'}
              style={{
                backgroundImage: `url("${iconMap.volume}")`
              }}
            />
            <div className={'X-audioCanvas-options-volume-slider'}>
              <Slider
                value={sliderValue}
                tooltipPlacement="top"
                onChange={ev => handleChangeSlider(ev)}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};